package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.constants.message.NewsAutoScanConstants;
import com.heima.common.constants.message.NewsUpOrDownConstants;
import com.heima.common.constants.message.PublishArticleConstants;
import com.heima.common.constants.wemedia.WemediaConstants;
import com.heima.common.exception.CustException;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.threadlocal.WmThreadLocalUtils;
import com.heima.model.wemedia.dtos.NewsAuthDTO;
import com.heima.model.wemedia.dtos.WmNewsDTO;
import com.heima.model.wemedia.dtos.WmNewsPageReqDTO;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.model.wemedia.vos.WmNewsVO;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.service.WmNewsService;
import io.seata.common.util.CollectionUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@Service
public class WmNewsServiceImpl extends ServiceImpl<WmNewsMapper, WmNews> implements WmNewsService {

    @Value("${file.oss.web-site}")
    String webSite;

    /**
     * 查询所有自媒体文章
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult findList(WmNewsPageReqDTO dto) {
        //1 参数检查
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        dto.checkParam();

        //2 进行条件封装，
        LambdaQueryWrapper<WmNews> wrapper = new LambdaQueryWrapper<>();
        // 文章标题模糊查询
        wrapper.like(StringUtils.isNotBlank(dto.getKeyword())
                , WmNews::getTitle, dto.getKeyword());
        // 频道id
        wrapper.eq(dto.getChannelId() != null
                , WmNews::getChannelId, dto.getChannelId());
        // 文章状态
        wrapper.eq(dto.getStatus() != null
                , WmNews::getStatus, dto.getStatus());
        // 发布时间 >= 开始时间
        wrapper.ge(dto.getBeginPubDate() != null, WmNews::getPublishTime, dto.getBeginPubDate());
        // 发布时间 <= 开始时间
        wrapper.le(dto.getEndPubDate() != null, WmNews::getPublishTime, dto.getBeginPubDate());

        // 3. 获取当前已登录自媒体人的信息
        WmUser wmUser = WmThreadLocalUtils.getUser();
        if (wmUser == null) {
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN);
        }

        // 4. 根据条件查询
        wrapper.eq(WmNews::getUserId, wmUser.getId());
        // 按照创建日期倒序
        wrapper.orderByDesc(WmNews::getCreatedTime);

        // 5. 分页条件构建
        Page<WmNews> page = new Page<>(dto.getPage(), dto.getSize());

        //5.  执行分页查询
        IPage<WmNews> pageResult = this.page(page, wrapper);

        //6.  将查询到的数据，封装为响应数据
        PageResponseResult result = new PageResponseResult(dto.getPage(), dto.getSize(), pageResult.getTotal());
        result.setHost(webSite); // 设置图片的IP或域名
        result.setData(pageResult.getRecords());
        return result;
    }

    @Resource
    private RabbitTemplate rabbitTemplate;

    /**
     * 提交新闻
     *
     * @param wmNewsDto
     * @return 通用的结果返回类
     */
    @Transactional
    @Override
    public ResponseResult submitNews(WmNewsDTO wmNewsDto) {
        // 1.参数校验
        if (StringUtils.isBlank(wmNewsDto.getContent())) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }

        // 2. 校验是否登陆
        WmUser user = WmThreadLocalUtils.getUser();
        if (user == null) {
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN);
        }

        // 3. 构建wmNews对象
        WmNews wmNews = new WmNews();
        // 将dto参数里面的值设置到wmNews
        BeanUtils.copyProperties(wmNewsDto, wmNews);
        //如果文章布局是自动，需要设置为null
        if (wmNewsDto.getType().equals(WemediaConstants.WM_NEWS_TYPE_AUTO)) {
            wmNews.setType(null);
        }
        // 处理dto参数 images封面集合 转换成 字符串
        String images = imageListToStr(wmNewsDto.getImages(), webSite);
        wmNews.setImages(images);
        wmNews.setUserId(user.getId());

        this.saveOrUpdateWmNews(wmNews);
        // 如果是草稿  直接返回
        if (WemediaConstants.WM_NEWS_DRAFT_STATUS.equals(wmNewsDto.getStatus())) {
            return ResponseResult.okResult();
        }

        // TODO 3 关联文章和素材的关系 -> wm_news_material

        // TODO 3.1 解析出文章内容中关联图片路径(去掉图片域名前的域名)
        List<String> imageUrlsInContent = parseContentImages(wmNewsDto.getContent());

        // TODO 3.2 关联 文章内容图片 和 素材 关系
        if (CollectionUtils.isNotEmpty(imageUrlsInContent)) {
            saveRelativeInfo(imageUrlsInContent, wmNews.getId(),
                    WemediaConstants.WM_CONTENT_REFERENCE);
        }

        // TODO 3.3 关联 文章封面图片和素材关系  封面可能是选择自动或者是无图
        saveRelativeInfoForCover(wmNewsDto, imageUrlsInContent, wmNews);

        // 3.4 发送待审核消息 -> rabbitmq
        rabbitTemplate.convertAndSend("", NewsAutoScanConstants.WM_NEWS_AUTO_SCAN_QUEUE, wmNews.getId());
        log.info("成功发送待审核消息 by rabbitmq 待审核的文章id为：{}", wmNews.getId());
        return ResponseResult.okResult();
    }

    /**
     * 【3.3】 关联文章封面中的图片和素材关系
     *
     * @param dto       前端用户选择封面信息数据
     * @param materials 从内容中解析的图片列表
     * @param wmNews    文章ID
     */
    private void saveRelativeInfoForCover(WmNewsDTO dto, List<String> materials, WmNews wmNews) {
        // 前端用户选择的图
        List<String> coverImgUrls = dto.getImages();

        // 自动获取封面 ****
        if (WemediaConstants.WM_NEWS_TYPE_AUTO.equals(dto.getType())) {
            int materialSize = materials.size();

            // 手动判断文章封面图片类型
            if (materialSize > 0 && materialSize <= 2) {  // 单图
                coverImgUrls = materials.stream().limit(1).collect(Collectors.toList());
                wmNews.setType(WemediaConstants.WM_NEWS_SINGLE_IMAGE);
            } else if (materialSize > 2) { // 多图
                coverImgUrls = materials.stream().limit(3).collect(Collectors.toList());
                wmNews.setType(WemediaConstants.WM_NEWS_MANY_IMAGE);
            } else {  // 无图
                wmNews.setType(WemediaConstants.WM_NEWS_NONE_IMAGE);
            }

            if (coverImgUrls != null && coverImgUrls.size() > 0) {
                // 将图片集合 转为字符串  url1, url2, url3
                wmNews.setImages(imageListToStr(coverImgUrls, webSite));
            }
            updateById(wmNews);
        }

        // 已指定好封面类型
        // 保存图片列表和素材的关系
        if (coverImgUrls != null && coverImgUrls.size() > 0) {
            coverImgUrls = coverImgUrls
                    .stream()
                    .map(imageUrl ->
                            imageUrl.replace(webSite, "")
                                    .replace(" ", ""))
                    .collect(Collectors.toList());

            saveRelativeInfo(coverImgUrls, wmNews.getId(),
                    WemediaConstants.WM_IMAGE_REFERENCE);
        }
    }

    @Resource
    WmMaterialMapper wmMaterialMapper;

    /**
     * 保存素材和文章关系
     *
     * @param imageUrls 素材列表
     * @param newsId    文章ID
     * @param type      类型 0：内容素材  1：封面素材
     */
    private void saveRelativeInfo(List<String> imageUrls, Integer newsId, Short type) {
        //1 查询文章内容中的图片对应的素材ID by imageUrls and userId
        List<Integer> wmMaterialIds = wmMaterialMapper.selectRelationsIds(imageUrls,
                WmThreadLocalUtils.getUser().getId());

        //2 判断文章中的素材是否在素材表中真实存在
        if (CollectionUtils.isEmpty(wmMaterialIds) ||
                wmMaterialIds.size() < imageUrls.size()) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "文章内容中的相关素材缺失,保存文章失败");
        }

        //3 保存素材与文章的关系（wm_news_material）
        wmNewsMaterialMapper.saveRelations(wmMaterialIds, newsId, type);
    }

    /**
     * 抽取文章内容中 所引用的所有图片
     *
     * @param content 文章内容
     * @return
     */
    private List<String> parseContentImages(String content) {
        List<Map> contents = JSON.parseArray(content, Map.class);
        // 遍历文章内容   将所有 type为image的 value获取出来  去除前缀路径
        return contents.stream()
                // 过滤type=image所有的集合
                .filter(map -> map.get("type").equals(WemediaConstants.WM_NEWS_TYPE_IMAGE))
                // 获取到image下的value  图片url
                .map(x -> (String) x.get("value"))
                // 图片url去除前缀
                .map(url -> url.replace(webSite, "").replace(" ", ""))
                // 去除重复的路径
                .distinct()
                // stream 转成list集合
                .collect(Collectors.toList());
    }

    @Resource
    WmNewsMaterialMapper wmNewsMaterialMapper;

    /**
     * 保存或修改文章
     *
     * @param wmNews 文章对象（前端传递）
     */
    private void saveOrUpdateWmNews(WmNews wmNews) {
        wmNews.setCreatedTime(new Date());
        wmNews.setUserId(WmThreadLocalUtils.getUser().getId());
        wmNews.setSubmitedTime(new Date());
        wmNews.setEnable(WemediaConstants.WM_NEWS_UP); // 上架
        if (wmNews.getId() == null) { // 保存操作
            save(wmNews);
        } else {  // 修改
            // 如果是修改新闻内容，采用暴力删除 wm_news_material中的数据 by newsId and userId
            wmNewsMaterialMapper
                    .delete(Wrappers.<WmNewsMaterial>lambdaQuery()
                            .eq(WmNewsMaterial::getNewsId, wmNews.getId()));
            // 更新 wm_news 表中的数据
            this.updateById(wmNews);
        }
    }

    @Override
    public ResponseResult findWmNewsById(Integer id) {
        //1 参数检查
        if (id == null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2 执行查询
        WmNews wmNews = getById(id);
        if (wmNews == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //3 返回结果
        ResponseResult result = ResponseResult.okResult(wmNews);
        result.setHost(webSite);
        return result;
    }

    /**
     * 图片列表转字符串，并去除图片前缀
     *
     * @param images  图片列表
     * @param webSite 图片前缀
     */
    private String imageListToStr(List<String> images, String webSite) {
        if(CollectionUtils.isEmpty(images)) {
            return  "image list to str error";
        }
        return images.stream()  // 获取流
                .map((url) -> url.replace(webSite, ""))  // 对流数据的中间操作
                .collect(Collectors.joining(","));
    }

    private List<String> imageStrToList(String images, String webSite) {
        String[] splitImages = images.split(",");
        if (splitImages == null) {
            return null;
        }
        return Arrays.stream(splitImages)
                .map((url) -> url.replace(webSite, "")) // 去除图片url的前缀域名
                .collect(Collectors.toList());
    }

    /**
     * 删除新闻（删除新闻时，新闻必须先处于下架）
     *
     * @param id 编号
     * @return 通用的结果返回类
     */
    @Transactional
    @Override
    public ResponseResult delNews(Integer id) {
        //1.检查参数
        if (id == null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID, "文章Id不可缺少");
        }
        //2.获取新闻数据
        WmNews wmNews = this.getById(id);
        if (wmNews == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "文章不存在");
        }

        //3.判断当前文章的状态  status==9  enable == 1 审核通过且已上架 不能删除
        if (wmNews.getStatus().equals(WmNews.Status.PUBLISHED.getCode())
                && wmNews.getEnable().equals(WemediaConstants.WM_NEWS_UP)) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "文章已发布，不能删除");
        }

        //4.去除素材与文章的关系
        wmNewsMaterialMapper.delete(
                Wrappers
                        .<WmNewsMaterial>lambdaQuery()
                        .eq(WmNewsMaterial::getNewsId, wmNews.getId())
        );

        //5.删除文章
        this.removeById(wmNews.getId());
        return ResponseResult.okResult();
    }

    @Override
    public ResponseResult downOrUp(WmNewsDTO dto) {
        //1.检查参数
        if (dto == null || dto.getId() == null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        Short enable = dto.getEnable();
        if (enable == null ||
                (!WemediaConstants.WM_NEWS_UP.equals(enable) && !WemediaConstants.WM_NEWS_DOWN.equals(enable))) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID, "上下架状态错误");
        }
        //2.查询文章
        WmNews wmNews = getById(dto.getId());
        if (wmNews == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "文章不存在");
        }
        //3.判断文章是否发布
        if (!wmNews.getStatus().equals(WmNews.Status.PUBLISHED.getCode())) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "当前文章不是发布状态，不能上下架");
        }
        //4.修改文章状态，同步到app端（后期做）TODO
        update(Wrappers.<WmNews>lambdaUpdate()
                .eq(WmNews::getId, dto.getId())
                .set(WmNews::getEnable, enable));

        sendNewsUpOrDownMsgToRabbit(enable, wmNews); // 发送消息到RabbitMQ

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    private void sendNewsUpOrDownMsgToRabbit(Short enable, WmNews wmNews) {
        Long articleId = wmNews.getArticleId();
        if(WemediaConstants.WM_NEWS_UP.equals(enable)){
            // 上架, 往rabbitmq中发消息
            rabbitTemplate.convertAndSend(
                    NewsUpOrDownConstants.NEWS_UP_OR_DOWN_EXCHANGE,
                    NewsUpOrDownConstants.NEWS_UP_ROUTE_KEY,
                    articleId
            );
            log.info("成功发送文章上架消息，articleId = {}", articleId);
        } else {
            // 下架
            rabbitTemplate.convertAndSend(
                    NewsUpOrDownConstants.NEWS_UP_OR_DOWN_EXCHANGE,
                    NewsUpOrDownConstants.NEWS_DOWN_ROUTE_KEY,
                    articleId
            );
            log.info("成功发送文章下架消息，articleId = {}", articleId);
        }
    }


    @Resource
    private WmNewsMapper wmNewsMapper;

    @Override
    public ResponseResult findPendingList(NewsAuthDTO newsAuthDTO) {
        // 1. 校验参数
        if (newsAuthDTO == null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID, "请求体内容不能为空");
        }
        // 2. 分页查询待审核的文章列表
        // 2.1 设置当前页
        Integer currentPage = newsAuthDTO.getPage();
        Integer size = newsAuthDTO.getSize();
        newsAuthDTO.setPage((currentPage - 1) * size);
        if (StringUtils.isNotBlank(newsAuthDTO.getTitle())) {
            newsAuthDTO.setTitle("%" + newsAuthDTO.getTitle() + "%");
        }else {
            newsAuthDTO.setTitle("");
        }

        // 3 查询列表
        List<WmNewsVO> data = wmNewsMapper.findListAndPage(newsAuthDTO);
        long count = wmNewsMapper.findListCount(newsAuthDTO);

        // 4. 封装返回结果
        PageResponseResult responseResult = new PageResponseResult(currentPage, size, count);
        responseResult.setData(data);
        return responseResult;
    }

    /**
     * 自媒体文章人工审核
     * @param status 2  审核失败  4 审核成功
     * @param dto
     * @return
     */
    @Override
    public ResponseResult updateStatus(Short status, NewsAuthDTO dto) {
        //1.参数检查
        if(dto == null || dto.getId() == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.查询文章
        WmNews wmNews = getById(dto.getId());
        if(wmNews == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        // 检查文章状态 不能为9  已发布
        if (wmNews.getStatus().equals(WmNews.Status.PUBLISHED.getCode())) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW,"文章已发布");
        }
        //3.修改文章状态
        wmNews.setStatus(status);
        if(StringUtils.isNotBlank(dto.getMsg())){
            wmNews.setReason(dto.getMsg());
        }
        updateById(wmNews);

        // TODO 通知定时发布文章
        if (status == WmNews.Status.ADMIN_SUCCESS.getCode()) {
            delayPublishWmNews(wmNews);
        }
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    private void delayPublishWmNews(WmNews wmNews) {
        // 1. 处理时间格式
        // 1.1 获取发布时间
        long publishTime = wmNews.getPublishTime().getTime();
        // 1.2 获取当前时间
        long now = new Date().getTime();
        // 1.3 计算剩余时间
        long remainTime = publishTime - now;

        // 2. 发送消息 by rabbitTemplate
        rabbitTemplate.convertAndSend(
                PublishArticleConstants.DELAY_DIRECT_EXCHANGE, // 指定交换机名称
                PublishArticleConstants.PUBLISH_ARTICLE_ROUTE_KEY, // 指定路由键名称
                // 为了避免延迟队列中的wmNews可能与主表中的wmNews不一致，故将id作为消息体发送给delayed队列
                wmNews.getId(),
                message -> {
                    MessageProperties properties = message.getMessageProperties();
                    properties.setHeader("x-delay", remainTime <=0 ? 0 : remainTime);
                    return message;
                }
        );
        log.info("文章自动审核通过，已发送到delayed队列，等待定时发布, 文章id: {}, 当前时间：{}", wmNews.getId(), LocalDateTime.now());
    }
}